package com.zz.examination.repository.impl;

import com.zz.examination.entity.User;
import com.zz.examination.repository.UserRepository;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class UserRepositoryImpl implements UserRepository {

    @Resource
    MongoTemplate mongoTemplate;

    @Override
    public User getOrSave(String userName) {
        Criteria criteria = Criteria.where("userName").is(userName);
        User user = mongoTemplate.findOne(new Query(criteria), User.class);
        if (user == null) {
            user = User.builder().id(String.valueOf(new Date().getTime())).userName(userName).build();
            mongoTemplate.insert(user);
        }
        return user;
    }
}
